<template>
   <div class="app-container">
      <el-row :gutter="20">
         <!--部门数据-->
         <el-col :span="4" :xs="24">
            <div class="head-container">
               <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
               />
            </div>
            <div class="head-container">
               <el-tree
                  :data="deptOptions"
                  :props="{ label: 'deptName', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="deptTreeRef"
                  node-key="id"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
               />
            </div>
         </el-col>
         <!--用户数据-->
         <el-col :span="20" :xs="24">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
               <el-form-item label="用户名称" prop="name">
                  <el-input
                     v-model="queryParams.name"
                     placeholder="请输入用户名称"
                     clearable
                     style="width: 240px"
                     @keyup.enter="handleQuery"
                  />
               </el-form-item>
               <el-form-item label="手机号码" prop="phone">
                  <el-input
                     v-model="queryParams.phone"
                     placeholder="请输入手机号码"
                     clearable
                     style="width: 240px"
                     @keyup.enter="handleQuery"
                  />
               </el-form-item>
               <el-form-item label="创建时间" style="width: 308px;">
                  <el-date-picker
                     v-model="dateRange"
                     value-format="YYYY-MM-DD"
                     type="daterange"
                     range-separator="-"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
					 @change="dateRangeFun"
                  ></el-date-picker>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button
                     type="primary"
                     plain
                     icon="Plus"
                     @click="handleAdd"
					 v-hasPermi="['system:user:add']"
                  >新增</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     type="danger"
                     plain
                     icon="Delete"
                     :disabled="multiple"
                     @click="handleDelete"
					 v-hasPermi="['system:user:remove']"
                  >删除</el-button>
               </el-col>
               <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
               <el-table-column type="selection" width="50" align="center" />
               <el-table-column label="姓名" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
               <el-table-column label="登录帐号" align="center" key="loginName" prop="loginName" :show-overflow-tooltip="true" />
               <el-table-column label="手机号码" align="center" key="phone" prop="phone" width="120" />
               <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
                  <template #default="scope">
                     <span>{{ parseTime(scope.row.createTime) }}</span>
                  </template>
               </el-table-column>
               <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="修改" v-if="scope.row.id !== '0'" placement="top">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                     </el-tooltip>
                     <el-tooltip content="删除" v-if="scope.row.id !== '0'" placement="top">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                     </el-tooltip>
                     <el-tooltip content="重置密码" v-if="scope.row.id !== '0'" placement="top">
                         <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)"></el-button>
                     </el-tooltip>
                  </template>
               </el-table-column>
            </el-table>
            <pagination
               v-show="total > 0"
               :total="total"
               v-model:page="queryParams.pageNum"
               v-model:limit="queryParams.pageSize"
               @pagination="getList"
            />
         </el-col>
      </el-row>

      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
         <el-form :model="form" :rules="rules" ref="userRef" label-width="100px">
            <el-row>
               <el-col :span="12">
                  <el-form-item label="用户姓名" prop="name">
                     <el-input v-model="form.name" placeholder="请输入用户姓名" maxlength="30" />
                  </el-form-item>
               </el-col>
				<el-col :span="12">
				   <el-form-item label="手机号码" prop="phone">
				      <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
				   </el-form-item>
				</el-col>
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item v-if="form.userId == undefined" label="登录帐号" prop="loginName">
                     <el-input v-model="form.loginName" placeholder="请输入登录帐号" maxlength="30" />
                  </el-form-item>
               </el-col>
			   <el-col :span="12">
			      <el-form-item v-if="form.userId == undefined" label="登录密码" prop="password">
			         <el-input v-model="form.password" placeholder="请输入登录密码" type="password" maxlength="20" show-password />
			      </el-form-item>
			   </el-col>
               
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="用户性别">
                     <el-select v-model="form.sex" placeholder="请选择">
                        <el-option
                           v-for="dict in userSexList"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"
                        ></el-option>
                     </el-select>
                  </el-form-item>
               </el-col>
			   <el-col :span="12">
			      <el-form-item label="角色">
			         <el-select v-model="form.roleIds" multiple placeholder="请选择">
			            <el-option
			               v-for="item in roleOptions"
			               :key="item.id"
			               :label="item.roleName"
			               :value="item.id"
			               :disabled="item.roleStatus == 1"
			            ></el-option>
			         </el-select>
			      </el-form-item>
			   </el-col>
            </el-row>
			<el-row>
			   <el-col :span="24">
			      <el-form-item label="部门">
			        <el-tree-select
			            v-model="form.deptId"
			            :data="deptOptions"
			            :props="{ value: 'id', label: 'deptName', children: 'children' }"
			            value-key="id"
			            placeholder="选择部门"
			            check-strictly
			        />
			      </el-form-item>
			   </el-col>
			</el-row>
            <el-row>
               <el-col :span="24">
                  <el-form-item label="备注">
                     <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入内容"></el-input>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { listUser, resetUserPwd, delUser, getUser, updateUser, addUser, delMultipleUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { roleAllList } from "@/api/system/role";

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");

const userList = ref([]);
const userSexList = ref([{label: '男', value: 'm'}, {label: '女', value: 'n'}])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data = reactive({
  form: {
	  sex: '',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },
  rules: {
    name: [{ required: true, message: "用户姓名不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户姓名长度必须介于 2 和 20 之间", trigger: "blur" }],
    loginName: [{ required: true, message: "登录帐号不能为空", trigger: "blur" }],
    password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }, { min: 5, max: 99, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
    // roleKey: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree() {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "id");
  });
};
/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(res => {
    loading.value = false;
    userList.value = res.data.rows;
    total.value = res.data.total;
  });
};
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的用户？').then(function () {
	if (row.id) {
		delUser(userIds).then(res => {
			getList();
			proxy.$modal.msgSuccess("删除成功");
		})
	} else {
		delMultipleUser(userIds).then(res => {
			getList();
			proxy.$modal.msgSuccess("删除成功");
		});
	}
  }).catch(() => {});
};
const dateRangeFun = () => {
	queryParams.value.createTime1 = dateRange.value[0]
	queryParams.value.createTime2 = dateRange.value[1]
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
};
/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
};
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.name + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 99 之间",
  }).then(({ value }) => {
    resetUserPwd(row.id, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
    });
  }).catch(() => {});
};
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    name: '',
    loginName: '',
    password: '',
    phone: '',
	roleIds: [],
    sex: '',
    remark: '',
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
  // getUser().then(response => {
  //   postOptions.value = response.posts;
  //   roleOptions.value = response.roles;
  //   open.value = true;
  //   title.value = "添加用户";
  //   form.value.password = initPassword.value;
  // });
};
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.id;
  getUser(userId).then(response => {
    form.value = response.data;
    form.value.roleIds = response.data.roleIds === '' ? [] : response.data.roleIds.split(',');
    open.value = true;
    title.value = "修改用户";
    form.password = "";
	getRoleList();
  });
};
const getRoleList = () => {
	roleAllList().then(res => {
		roleOptions.value = res.data
	})
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
		  form.value.roleIds = form.value.roleIds.length === 0 ? '' : form.value.roleIds.join(',');
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
		  form.value.roleIds = form.value.roleIds.length === 0 ? '' : form.value.roleIds.join(',');
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

getDeptTree();
getList();
</script>
